package com.yc.fav.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.fav.Utils;
import com.yc.fav.entity.User;
import com.yc.fav.mapper.UserMapper;
import com.yc.fav.vo.Result;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        ApplicationContext cxt = (ApplicationContext) servletContext.getAttribute("cxt");
        UserMapper userMapper = cxt.getBean(UserMapper.class);

        String name=req.getParameter("account");
        String pwd=req.getParameter("password");
        if(name==null||name.isBlank()){
            Utils.print(resp,new Result(0,"请输入账号",null));
            return;
        }
        if(pwd==null||pwd.isBlank()){
            Utils.print(resp,new Result(0,"请输入密码",null));
            return;
        }

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName,name);
        lqw.eq(User::getPwd,pwd);
        User user = userMapper.selectOne(lqw);
        if(user == null){
            Utils.print(resp,new Result(0,"用户名或密码错误!",null));
            return;
        }
        req.getSession().setAttribute("loginedUser",user);
        Utils.print(resp,new Result(1,"登录成功!",user.getId()));
    }
}
